/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * Glavna serverska klasa.
 */

package org.foment.gem;
import java.net.*;
import java.io.*;
import java.sql.*;
import config.TransferProtocol;
import java.util.*;
import org.foment.data.SqlDataResultSet;


/**
 *
 * @author dusan
 */
public class Server
{
    public static void main(String args[])
    {
        // prvo, uspostavljamo vezu sa bazom podataka...
        // server se loguje na bazu kao root. Klijenti ce vec imati
        // druga prava.
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            conn =  DriverManager.getConnection("jdbc:mysql://localhost/gem?user=root&password=test&useUnicode=true&characterEncoding=utf8");
            stat = conn.createStatement();
            stat.execute("SET NAMES 'utf8' COLLATE 'utf8_general_ci' ");
            rs = stat.executeQuery("SHOW VARIABLES LIKE 'character_set%'");

            while(rs.next())
            {
                //System.out.println(rs.getString("Variable_name") + " " + rs.getString("Value"));
            }
            rs = stat.executeQuery("SHOW VARIABLES LIKE 'collation%'");
            while(rs.next())
            {
                System.out.println(rs.getString("Variable_name") + " " + rs.getString("Value"));
            }
        }
        catch (ClassNotFoundException cnfe) {System.out.println("Server: " + cnfe.getMessage());}
        catch (SQLException se) {System.out.println("Server: " + se.getMessage());}
        System.out.println("Server: database connection established");
        
        try
        {
            ServerSocket server = new ServerSocket(TransferProtocol.PORT);
            for (int i = 0; ; i++)
            {
                // u petlji cekamo na vezu sa klijentom
                Socket client = server.accept();
                ServerHandler sh = new ServerHandler(client, i); // ubaciti client, i
                sh.start(); // zapocinje nit.
            }
        }
        catch (IOException e ){ System.err.println("Server: ServerSocket error " + e.getMessage());}
                
    }
    
    // podaci vezani za konekciju sa bazom.
    protected static Connection conn;
    protected static Statement stat;
    protected static ResultSet rs;
    // vektor konekcija. sadrzace sve veze sa klijentima, odnosno
    // to je vektor ServerHandler-a.
    protected static Vector connections  = new Vector();
}
